<template>
  <div class="second-child" ref="menu">
    <el-menu
      class="el-menu-vertical-demo"
    >
    <!-- 基本信息 -->
      <el-submenu index="1">
        <template slot="title">
            <span>基本信息</span>
        </template>
        <el-menu-item-group>
          <template slot="title">
            <el-form ref="form" :model="newEditForm" label-width="80px" :rules="rules">
                <el-form-item label="所属分类">
                    <span class="spanStyle" v-show="resultsText.oneName">{{'  ' + resultsText.oneName}}</span>
                    <span class="spanStyle" v-show="resultsText.twoName">{{'  »  ' +resultsText.twoName}}</span>
                    <span class="spanStyle" v-show="resultsText.threeName">{{'  »  ' +resultsText.threeName}}</span>
                    <span class="spanStyle" style="margin-left: 20px; color: #0091ea !important;cursor:pointer;" @click="backOne">编辑</span>
                </el-form-item>

                <el-form-item label="商品类型">
                    <el-select clearable  v-model="newEditForm.typeId" placeholder="请选择">
                        <el-option
                        v-for="item in typeArr"
                        :key="item.id"
                        :label="item.name"
                        :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>

                <el-form-item label="商品名称" prop="productName">
                    <el-input v-model="newEditForm.productName" style="width: 300px;" placeholder="清输入商品名称"></el-input>
                </el-form-item>

                <el-form-item label="商品简介">
                    <el-input type="textarea" :rows="4" style="width: 300px;" maxlength="300" show-word-limit v-model="newEditForm.shortDesc" placeholder="限定300字符以内"></el-input>
                </el-form-item>

                <el-form-item label="计量单位">
                    <el-input v-model="newEditForm.unit" style="width: 300px;" placeholder="输入中文或英文，例:g/元"></el-input>
                </el-form-item>
            </el-form>
          </template>
        </el-menu-item-group>
      </el-submenu>
      <!-- 扩展属性 -->
      <el-submenu index="2" v-if="expandData.length">
        <template slot="title">
            <span>扩展属性</span>
        </template>
        <el-menu-item-group>
          <template slot="title">
            <el-form ref="form1" status-icon :model="newEditForm" label-width="80px">
                <el-col>
                    <el-form-item  :label="item.name" v-for="(item, i) in expandData" :key="item.id">
                        
                        <el-checkbox-group v-model="expandCheckList">
                            <el-checkbox @change="expandChange(i,tag.valueStr, index)" :label="tag.valueStr" v-for="(tag, index) in item.valueList" :key="index"></el-checkbox>
                        </el-checkbox-group>

                        <el-input
                            class="input-new-tag"
                            v-if="inputVisible && i === curIndex"
                            v-model="item.inputValue"
                            ref="saveTagInput"
                            placeholder="请输入"
                            size="small"
                            @keyup.enter.native="handleInputConfirm(item, i)"
                            @blur="handleInputConfirm(item, i)"
                            >
                        </el-input>
                        <el-button v-else class="button-new-tag" size="small" @click="showInput(i)">+ 添加属性值</el-button>
                    </el-form-item>
                </el-col>
                

            </el-form>
          </template>
        </el-menu-item-group>
      </el-submenu>
      
      <!-- 库存 -->
      <el-submenu index="3">
        <template slot="title">
            <span>库存规格</span>
        </template>
        <el-menu-item-group>
          <template slot="title">
            <!-- 未开启规格状态 -->
            <div v-show="newEditForm.hasSku !== '1'">
                <el-form ref="form1" status-icon :model="newEditForm" label-width="80px" :rules="rules">

                    <el-form-item label="市场价" prop="salePrice">
                        <span class="price">￥</span>
                        <el-input v-model="newEditForm.price" style="width: 300px;"></el-input>
                    </el-form-item>

                    <el-form-item label="一口价" prop="salePrice">
                        <span class="price">￥</span>
                        <el-input v-model="newEditForm.skuList[0].salePrice" style="width: 300px;"></el-input>
                    </el-form-item>

                    <el-form-item label="成本价">
                        <span class="price">￥</span>
                        <el-input v-model="newEditForm.skuList[0].costPrice" style="width: 300px;"></el-input>
                    </el-form-item>

                    <el-form-item label="货号">
                        <el-input v-model="newEditForm.skuList[0].sku" style="width: 300px;"></el-input>
                    </el-form-item>

                    <el-form-item label="商品库存" prop="stock">
                        <el-input v-model="newEditForm.skuList[0].stock" style="width: 300px;"></el-input>
                    </el-form-item>

                    <el-form-item label="警戒库存" prop="warningStock">
                        <el-input v-model="newEditForm.skuList[0].warningStock" style="width: 300px;"></el-input>
                    </el-form-item>

                    <el-form-item label="开启规格" prop="hasSku" v-show="newEditForm.typeId">
                        <el-button size="mini" type="primary" @click="openSpec">开启规格</el-button>
                    </el-form-item>

                </el-form>
            </div>

            <!-- 开启规格状态 -->
            <div  v-show="newEditForm.hasSku === '1' && newEditForm.skuList.length">

                <div style="text-align: center;">
                    市场价： <el-input v-model="newEditForm.price" style="width: 300px;"></el-input>
                </div>

                <div style="display: flex;justify-content: space-between;margin: 10px 0;">
                    <el-button size="mini" type="primary" @click="editSpec">编辑规格</el-button>
                    <div>
                        批量填充：
                        <el-input v-model="editFrom2.salePrice" style="width: 100px;" placeholder="一口价"></el-input>
                        <el-input v-model="editFrom2.costPrice" style="width: 100px;" placeholder="成本价"></el-input>
                        <el-input v-model="editFrom2.stock" style="width: 100px;" placeholder="库存"></el-input>
                        <el-input v-model="editFrom2.warningStock" style="width: 100px;" placeholder="警告库存"></el-input>
                        <el-button size="mini" type="primary" @click="sureBoth">确定</el-button>
                    </div>
                </div>

                <el-table
                    border
                    size="mini"
                    :data="newEditForm.skuList"
                    style="width: 100%"
                >
                    <el-table-column type="index"></el-table-column>

                    <el-table-column v-for="(item, i) in newItem" :key="i" :label="item.name" width="60">
                        <template slot-scope="scope">
                            <span>{{tableItemList[scope.$index][i]}}</span>
                        </template>
                    </el-table-column>

                    <el-table-column prop="sku" label="货号" width="200">
                        <template slot-scope="scope">
                            <el-input v-model="scope.row.sku"></el-input>
                        </template>
                    </el-table-column>

                    <el-table-column prop="salePrice" label="一口价" width="150">
                        <template slot-scope="scope">
                            <el-input v-model="scope.row.salePrice"></el-input>
                        </template>
                    </el-table-column>

                    <el-table-column prop="costPrice" label="成本价" width="150">
                        <template slot-scope="scope">
                            <el-input v-model="scope.row.costPrice"></el-input>
                        </template>
                    </el-table-column>

                    <el-table-column prop="stock" label="库存" width="150">
                        <template slot-scope="scope">
                            <el-input v-model="scope.row.stock"></el-input>
                        </template>
                    </el-table-column>

                    <el-table-column prop="warningStock" label="警告库存" width="150">
                        <template slot-scope="scope">
                            <el-input v-model="scope.row.warningStock"></el-input>
                        </template>
                    </el-table-column>

                    <el-table-column label="操作">
                        <template slot-scope="scope">
                            <el-button size="mini" type="danger" @click="delCurSpec(scope.$index)">删除</el-button>
                        </template>
                    </el-table-column>
                </el-table>
                
            </div>
            

          </template>
        </el-menu-item-group>
      </el-submenu>
    </el-menu>
    <span v-html="navStyle"></span>

    <div style="text-align: center; margin-top: 20px;">
        <el-button size="mini" type="primary" @click="backOne">上一步</el-button>
        <el-button size="mini" type="primary" @click="next('third')">下一步</el-button>
    </div>

    <spec-dialog
        :visible="visible"
        :typeId="newEditForm.typeId"
        :editSpecData="newList"
        @cancel="cancel"
        @specList="specList">

    </spec-dialog>
  </div>
</template>

<script>
import {
    list,
    expandType,
    addExpandAttr,
    specs,
    addSpces
} from "@/api/agri-product/goodsType";
import SpecDialog from '../specDialog'
export default {
  name: "two",
  props: ['resultsText', 'newEditFormTwo'],
  components: {
      SpecDialog
  },
  data() {
    let checkSalePrice = (rule, value, callback) => {
        console.log(rule, value)
        value = parseFloat(value);
        console.log(rule, value)
        if (!value) {
          return callback(new Error('必须大于0.01元'));
        }
        setTimeout(() => {
          if (!Number.isInteger(value)) {
            callback(new Error('请输入数字值'));
          } else {
            if (value < 0.01) {
              callback(new Error('必须大于0.01元'));
            } else {
              callback();
            }
          }
        }, 1000);
      };

    let checkStock = (rule, value, callback) => {
        value = parseFloat(value);
        if (!value) {
          return callback(new Error('数据类型错误，只能输入整数型数值'));
        }
        setTimeout(() => {
          if (!Number.isInteger(value)) {
            callback(new Error('数据类型错误，只能输入整数型数值'));
          }else {
              callback();
          }
        }, 1000);
      };

    return {
        navStyle: `
            <style>
                .second-child .el-menu{
                    border-right: none;
                }
                .second-child .el-submenu__title {
                    padding-left: 20px;
                    border-bottom: 1px solid #e6e6e6;
                }
                .second-child .el-submenu__icon-arrow {
                    display: block !important;
                }
            </style>
        `,
        visible: false,
        typeArr: [],
        page: {
                pageSize: 10,
                currentPage: 1,
                total: 0
        },
        rules: {
                productName :[{required: true, message: '请输入商品名称', trigger: 'blur'}],
                // salePrice: [{validator: checkSalePrice, trigger: 'blur'}],
                // stock: [{validator: checkStock, trigger: 'blur'}],
                // warningStock: [{validator: checkStock, trigger: 'blur'}]
            },
        expandData: [],
        specsData: [],
        curIndex: '',
        inputVisible: false,
        newItem: [],
        newList: [], //编辑弹窗返回的数据
        newEditForm: {},
        editFrom2: {
            costPrice: '', //成本价
            salePrice: '', //一口价
            stock: '', //库存
            warningStock: '', //警告库存
        },
        expandCheckList: [],
        isAddExpand: true,
        isCreated: false,
        tableItemList: [],
        parentId: [],
        tableItemList: []
    };
  },
  created () {
    this.loadData(this.page)

    this.newEditForm = JSON.parse(JSON.stringify(this.newEditFormTwo))

    this.tableItemList = []
    this.parentId = []
    this.newEditForm.skuList.forEach((item, index) =>{
        this.newList.push(...JSON.parse(JSON.stringify(item.skuItemList)))
        this.tableItemList.push(JSON.parse(JSON.stringify(item.skuItemList)))
        item.skuItemList.forEach(items => {
            let flag = true;
            if (!this.parentId.length) {
                this.parentId.push(items.attrId)
            } else {
                this.parentId.forEach(attr => {
                    if (attr === items.attrId) {
                        flag = false;
                        return;
                    }
                })

                flag && this.parentId.push(items.attrId)
            }
        })
    })

    console.log(this.tableItemList,'11', this.parentId, 'kkkkkkkkkkk')

    specs(this.newEditForm.typeId).then(res => {
        let arr = [], list=[], flag = true;
        res.data.data.records.forEach(item => {
            arr.push(item)
            this.parentId.forEach(id => {
                id === item.id && this.newItem.push({
                    name: item.name
                })
            })
        })

        this.tableItemList.forEach((item, index) => {
            item.forEach((attr, i) => {
                
                arr.forEach((arrItems, k) => {
                    flag && (list[k] = []);
                    arrItems.valueList.forEach((items, j) => {
                        if (items.attrId === attr.attrId && items.id === attr.attrValueId) {
                            this.tableItemList[index][i] = items.valueStr;
                            flag && (list[k].push(j))
                        }
                    })
                    
                })
                flag = false;
            })
        })

    })

    
  },
  mounted () {
      this.$nextTick(() => {
          [...this.$refs.menu.getElementsByClassName('el-submenu__title')].map(item => item.click())
      })
  },
  methods: {
    // 规格列表
    skuItem () {
        specs(this.typeId).then(res => {
            this.skuList = res.data.data.records;
        })
    },
    queryId (id, valueId) {

    },
    // 下一步
    next() {
        console.log(this.newEditForm)
        let status = true;
        this.$refs['form'].validate((valid) => {
            if (valid) {
                
            } else {
                status = false;
                return false;
            }
        });
        this.$refs['form1'].validate((valid) => {
            if (valid) {
                
            } else {
                status = false;
                return false;
            }
        });

        status && this.$emit('next', 'third', this.newEditForm)
    },
    // 返回类型
    backOne () {
        this.$emit('back', 'first')
    },
    //请求table数据
    loadData(page, params = {}){
        this.loading = true;
        list(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
            this.typeArr = res.data.data.records;
            
        });	
    },
    // 扩展属性-添加属性值
    showInput(index) {
        this.curIndex = index;
        this.inputVisible = true;
        this.$nextTick(_ => {
            // 自动聚焦报错
            // this.$refs.saveTagInput.$refs.input.focus();
        });
    },
    //扩展属性勾选事件 
    expandChange (i, tag, index) {
        this.$nextTick(() => {
            if (this.isAddExpand) {
                this.newEditForm.extAttrList.push(this.expandData[i].valueList[index])
            } else {
                this.newEditForm.extAttrList.forEach((item, k) => {
                    if(item.valueStr === tag) {
                        this.newEditForm.extAttrList.splice(k, 1)
                    }
                })
            }
        })
    },
    // 扩展属性-添加属性值
    handleInputConfirm(item) {
        let inputValue = item.inputValue;
        if (inputValue) {
            let data = {};
            data.attrId = item.id;
            data.displaySeq = item.displaySeq ? 1 : 0;
            data.imageUrl = item.imageUrl;
            data.valueStr = item.inputValue;
            addExpandAttrValue(data).then(res => {
                this.$message({
                    type: 'success',
                    message: '添加成功!'
                });
               this.getExpend(this.newEditForm.typeId)
            }).catch(err => {
                this.$message({
                    type: 'info',
                    message: '添加失败失败'
                });
            })
            
        }
        this.inputVisible = false;
        item.inputValue = '';
    },
    //获取属性列表
    getExpend (typeId) {
        expandType(typeId).then(res => {
            // 清空属性列表
            // this.newEditForm.extAttrList = [];
            
            this.expandData = res.data.data.records;
            this.expandData.forEach(item => {
                item.value = item.value ? item.value.replace(/，/g, ',').split(',') : [];
                // this.newEditForm.extAttrList = [...this.newEditForm.extAttrList, ...item.valueList]

                //初始化扩展属性选中状态
                !this.isCreated && item.valueList.forEach(items => {
                    this.newEditForm.extAttrList.forEach(target => {
                        console.log(items.attrId === target.attrId, items.id === target.attrValueId)
                        if (items.attrId === target.attrId && items.id === target.attrValueId) this.expandCheckList.push(items.valueStr);
                    })
                })
            })
            this.isCreated = true;
            this.$nextTick(() => {
                [...this.$refs.menu.getElementsByClassName('el-submenu__title')].map((item, i) => {
                    i == 1 && item.click()
                })
            })
        })
    },
    // 开启规格
    openSpec () {
        this.visible = true;
        this.newEditForm.hasSku = '1'
    },
    //编辑规格
    editSpec () {
        this.visible = true;

    },
    //确定统一填充
    sureBoth () {
        this.newEditForm.skuList.forEach(item => {
            item.costPrice = this.editFrom2.costPrice; //成本价
            item.salePrice = this.editFrom2.salePrice; //一口价
            item.stock = this.editFrom2.stock; //库存
            item.warningStock = this.editFrom2.warningStock; //警告库存
        })
    },
    //关闭弹窗
    cancel () {
        this.visible = false;
    },
    //已保存的规格列表
    specList (list) {
        //判断弹窗返回的数组是否为空，如果是空数组，则清空所有数据，关闭规格
        if (!list.length) {
            this.newEditForm.hasSku = '0';

            // 清空数据
            this.newItem = [];
            this.newList = [];
            this.tableItemList = [];

            //清空规格列表数据
            this.newEditForm.skuList = [{
                    costPrice: '', //成本价
                    salePrice: '', //一口价
                    sku: '', //货号
                    stock: '', //库存
                    warningStock: '', //警告库存
                }]

            //关闭弹窗
            this.cancel()

            return;
        }

        this.newList = JSON.parse(JSON.stringify(list))
        let arr = [];
        // 去除空对象
        this.newList.forEach(item => {
           arr.push(item.value)
        })
        //清空规格列表数据
        this.newEditForm.skuList = []

        function getArrayByArrays(arrays) {
            var arr = [""];
            for(var i = 0;i<arrays.length;i++) {
                arr = getValuesByArray(arr,arrays[i]);
            }
            return arr;
        }
        
        function getValuesByArray(arr1,arr2) {
            var arr = [];
            for(var i=0;i<arr1.length;i++) {
                var v1 = arr1[i];
                for(var j=0;j<arr2.length;j++) {
                    var v2 = arr2[j].valueStr;
                    var value = v1+ '-' +v2;
                    arr.push(value);
                };
            };
            return arr;
        }

        //递归算出新数据
        var array = getArrayByArrays(arr);
        this.tableItemList = [];
        console.log(arr, array, 'array')
        //根据新数据生成列表
        array.forEach((item, index) => {
            item = item.substr(1);
            item = item.split('-');
            this.tableItemList.push(JSON.parse(JSON.stringify(item)))
            console.log(this.tableItemList, 'this.tableItemList')

            this.newItem = [];
            let skuItemList = []
            item.forEach((items, i) => {
                this.newItem.push({
                    attrName: items,
                    name: this.newList[i].name
                })

                let obj = this.newList[i].value.filter(item => (item.valueStr === items));
                skuItemList.push({
                    attrId: obj[0].attrId,
                    attrValueId: obj[0].id
                })
            })
            this.newEditForm.skuList.push({
                costPrice: '', //成本价
                salePrice: '', //一口价
                sku: '', //货号
                stock: '', //库存
                warningStock: '', //警告库存
                skuItemList: [...skuItemList]//规格列表
            })
        })
        
        console.log(this.newEditForm, this.newItem, 'this.newItem')
        //关闭弹窗
        this.cancel()
    },
    //删除当前规格
    delCurSpec (i) {
        this.newEditForm.skuList.splice(i, 1)
        //如果全部删完，则关闭规格
        if (this.newEditForm.skuList.length === 0) {
            this.newEditForm.hasSku = '0';
            this.newEditForm.skuList = [{
                    costPrice: '', //成本价
                    salePrice: '', //一口价
                    sku: '', //货号
                    stock: '', //库存
                    warningStock: '', //警告库存
                }]
            // 清空数据
            this.newItem = [];
            this.newList = [];
            this.tableItemList = [];
        }
    }
  },

  watch: {
    'newEditForm.typeId' (cur) {
        console.log(cur, 'cur')
        if (cur) {
            this.getExpend(cur)
        } else {
            this.expandData = []
        }
    },
    expandCheckList (cur, pre) {
        this.isAddExpand = cur.length > pre.length ? true : false;
    }
  }
};
</script>

<style scoped>
.spanStyle {
    color: #000 !important;
    font-size: 12px;
}
.price {
    position: relative;
    left: 6px;
    min-width: 30px;
    line-height: 1;
    border: 1px solid #ddd;
    width: auto !important;
    padding: 11px 7px !important;
    border-right: 0;
    border-radius: 3px 0 0 3px !important;
    text-align: center;
    background-color: #eee;
    color: #333;
}
.el-tag + .el-tag {
    margin-left: 10px;
  }
  .button-new-tag {
    margin-left: 10px;
    height: 32px;
    line-height: 30px;
    padding-top: 0;
    padding-bottom: 0;
  }
.input-new-tag {
    width: 90px;
    margin-left: 10px;
    vertical-align: bottom;
  }
</style>